<template>
  <!-- 运行监测-树组件 -->
  <!-- {{ selectedKeys }} -->
  <div class="monitor-tree">
    <div class="tree__search p-4">
      <a-input
        v-model:value.trim="searchValue"
        :placeholder="props.searchPlaceholder"
        maxLength="100"
      >
        <template #suffix>
          <i class="font_family icon-sousuo search-icon"></i>
        </template>
      </a-input>
    </div>
    <a-spin :spinning="loading" class="w-full">
      <div v-if="!loading">
        <a-tree
          :disabled="disabled"
          v-if="filteredTreeData?.length"
          :defaultExpandAll="true"
          :blockNode="true"
          :tree-data="filteredTreeData"
          @select="handleSelect"
          :autoExpandParent="true"
          class="side-tree"
          :fieldNames="{ children: 'children', title: 'label', key: 'mainId' }"
          v-model:selectedKeys="selectedKeys"
        >
          <template #title="{ label }">
            <div class="ellipsis-label" :title="label">
              {{ label }}
            </div>
          </template>
        </a-tree>
        <a-empty v-else :image="simpleImage" />
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import type { TreeProps } from 'ant-design-vue'
import { onBeforeMount, ref, computed } from 'vue'
import { getOrgTree } from '@/api/organization'
import { Empty } from 'ant-design-vue'
import { cloneDeep } from 'lodash'

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

const emit = defineEmits(['updateCurrent', 'updateRootId', 'updateRootName'])

const props = defineProps({
  searchPlaceholder: {
    type: String,
    default: '请输入'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  defaultSelectNode: {
    // defaultSelectNode 默认选中节点的id
    type: String,
    default: ''
  }
})

// 顶部搜索框
const searchValue = ref('')
// 根据输入框内容对节点进行过滤,需要过滤机构,输入内容后只显示站点
const filteredTreeData = computed(() => {
  const filterTree = (data: any[]) => {
    return data.filter((node) => {
      const text = node.label

      // 不显示机构节点
      let nodeMatches
      if (node.type === 0 && searchValue.value.toString().length !== 0) {
        nodeMatches = false
      } else {
        nodeMatches = text.includes(searchValue.value)
      }

      if (nodeMatches) {
        return true
      }

      if (node.children) {
        node.children = filterTree(node.children)
        return node.children.length > 0
      }

      return false
    })
  }

  const res = cloneDeep(treeData.value)
  return filterTree(res as any[])
})

const treeData = ref<TreeProps['treeData']>([])
const loading = ref(false)
// const rootId = ref()
const rootItem = ref()

// 获取组织机构站点树
const getOrgTreeFun = async () => {
  loading.value = true
  getOrgTree()
    .then(async (res) => {
      const _data = cloneDeep(res)
      // 禁用组织机构节点
      treeData.value = await addDisabledToTree(_data)
      // 默认选中节点
      if (props.defaultSelectNode) {
        // 选中路由传过来的节点
        console.log(
          '选中路由传过来的节点-props.defaultSelectNode: ',
          props.defaultSelectNode
        )
        selectedKeys.value = [props.defaultSelectNode]
        emit('updateCurrent', {
          mainId: props.defaultSelectNode
        })
      } else {
        // 选中第一个站点节点
        const firstNode = await getFirstSiteNode(_data)
        if (firstNode) {
          selectedKeys.value = [firstNode.mainId]
          emit('updateCurrent', firstNode)
        }
      }
      loading.value = false
    })
    .catch(() => {
      treeData.value = []
      loading.value = false
    })
}

// 禁用机构节点
function addDisabledToNode(node: any) {
  if (node.type === 0) {
    node.disabled = true
  }
  if (node.children) {
    node.children = node.children.map((child: any) => addDisabledToNode(child))
  }
  return node
}
function addDisabledToTree(tree: any) {
  return tree.map((node: any) => addDisabledToNode(node))
}

// 返回第一个站点节点ID
const getFirstSiteNode: any = (nodes: any) => {
  for (const node of nodes) {
    if (node.type === 1) {
      return node
    } else if (node.children !== undefined && node.children.length > 0) {
      const result = getFirstSiteNode(node.children)
      if (result !== null) {
        return result
      }
    }
  }
  return null
}

onBeforeMount(() => {
  getOrgTreeFun()
})

// 选中节点
const currentNode = ref()
const handleSelect = (
  selectedKeys: any,
  e: { selected: boolean; selectedNodes: any }
) => {
  // eslint-disable-next-line eqeqeq
  if (e.selectedNodes[0] == undefined) {
    currentNode.value = rootItem.value
  } else {
    currentNode.value = e.selectedNodes[0]
  }
  emit('updateCurrent', currentNode.value)
}

const selectedKeys = ref<string[] | number[]>([])

const setSelectedKeys = (value: string[] | number[]) => {
  selectedKeys.value = value
  // if (value.length === 0 && treeData.value && treeData.value.length > 0) {
  //   emit('updateRootId', treeData.value[0].mainId)
  //   rootId.value = treeData.value[0].mainId
  //   emit('updateRootName', treeData.value[0].label)
  //   emit('updateCurrent', treeData.value[0]) // 选中第一个节点
  // }
}

defineExpose({ setSelectedKeys })
</script>

<style lang="less">
.monitor-tree {
  // overflow-x: hidden;
  overflow-y: auto;
  width: 15.88rem;
  height: 100%;
  background-size: 100% 100%;
  background-color: transparent;
  border: none;
  background-image: url('/src/assets/images/tree-bg.png');

  .search-icon {
    color: @active-text-color;
    cursor: pointer;
  }

  .ant-tree-title {
    .ellipsis-label {
      overflow: hidden;
      width: 120px;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }

    .ant-tree-indent-unit {
      width: 16px;
    }
  }
}
</style>
